﻿#include "scroll_mode_thread.h"
#include <iostream>

void ScrollModeADCThread::start() {
  thread_is_running_ = true;
  
  auto base_device = base_device_.lock();
  if (!base_device) {
    return;
  }
  
  data_length_threshold_ = base_device->GetCurrentDataLength();
  data_.resize(base_device->GetADCLegalChannelSize());
  for (int i = 0; i < data_.size(); i++) {
    data_[i].reserve(2 * data_length_threshold_);
  }
  
  // 启动线程
  thread_ = std::thread(&ScrollModeADCThread::run, this);
}

void ScrollModeADCThread::quit() {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    thread_is_running_ = false;
  }
  cv_.notify_one();
  
  if (thread_.joinable()) {
    thread_.join();
  }
}

void ScrollModeADCThread::run() {
  while (thread_is_running_) {
    bool success = ReadADCData();
    
    if (!success) {
      // 添加短暂休眠以避免CPU占用过高
      std::this_thread::sleep_for(std::chrono::microseconds(10));
      continue;
    }
    
    current_data_length_++;
    
    if (current_data_length_ == data_length_threshold_) {
      current_data_length_ = 0;
      
      // 使用回调函数代替信号槽
      if (data_callback_) {
        data_callback_(data_);
      }
      
      for (auto &i: data_) {
        i.clear();
        i.reserve(2 * data_length_threshold_);
      }
    }
  }
}

bool ScrollModeADCThread::ReadADCData() {
  bool success = false;
  auto base_device = base_device_.lock();
  if (!base_device) {
    return false;
  }
  
  const auto channel_number = base_device->GetADCLegalChannel().size();
  for (int i = 0; i < channel_number; i++) {
    float temp_data = 0;
    if (!base_device->TryReadADCData(i, &temp_data)) {
      continue;
    }
    
    data_[i].emplace_back(temp_data);
    success = true;
  }
  
  return success;
}
